/* eslint-disable linebreak-style */
/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable camelcase */
/* eslint-disable no-unused-vars */
/* eslint-disable no-underscore-dangle */
/* eslint-disable no-async-promise-executor */
/* eslint-disable class-methods-use-this */
const Koa = require('koa');
const Router = require('koa-router');
const { koaBody } = require('koa-body');
const path = require('path');
const fs = require('fs');
const cors = require('@koa/cors');

const ocr_api20210707 = require('@alicloud/ocr-api20210707');
const Util = require('@alicloud/tea-util');
const Stream = require('@alicloud/darabonba-stream');
const { createWorker, recognize } = require('tesseract.js');

const { Client } = require('./client');

const app = new Koa();
const router = new Router();
const port = 3000;

app.use(cors());

// 配置 koa-body 处理文件上传
app.use(
  koaBody({
    multipart: true,
    formidable: {
      uploadDir: path.join(__dirname, 'uploads'), // 上传文件保存目录
      keepExtensions: true, // 保留文件扩展名
    },
  }),
);

// 创建 uploads 目录（如果不存在）
if (!fs.existsSync(path.join(__dirname, 'uploads'))) {
  fs.mkdirSync(path.join(__dirname, 'uploads'));
}

// 定义文件上传路由
router.post('/uploadfile', async (ctx) => {
  const { files } = ctx.request; // 获取上传的文件

  const content = await Client.main(files.file.newFilename);

  fs.unlink(`./uploads/${files.file.newFilename}`, (err) => {
    if (err) {
      // 如果删除文件时发生错误，打印错误信息
      return console.error(err);
    }
    // 文件删除成功
    console.log(`${files.file.newFilename} was deleted successfully ${new Date()}`);
    return null;
  });

  ctx.body = {
    data: content?.split('【').join('【'),
    message: 'File uploaded successfully',
    filename: 'ok',
  };
});

router.post('/ocrByTesseract', async (ctx) => {
  const { files } = ctx.request; // 获取上传的文件

  const res = await recognize(
    `./uploads/${files.file.newFilename}`,
    'chi_sim',
  );
  console.log(res.data.text);

  fs.unlink(`./uploads/${files.file.newFilename}`, (err) => {
    if (err) {
      // 如果删除文件时发生错误，打印错误信息
      return console.error(err);
    }
    // 文件删除成功
    console.log(`${files.file.newFilename} was deleted successfully`);
    return null;
  });
  if (res.data.text) {
    ctx.body = {
      data: res.data.text,
      message: 'File uploaded successfully',
      filename: 'ok',
    };
    return;
  }

  ctx.body = {
    data: '',
    message: 'File uploaded successfully',
    filename: 'ok',
  };
});

app.use(router.routes()).use(router.allowedMethods());

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});
